<template>
  <div id="app">

    
    <!-- <HelloWorld msg="Welcome to Your Vue.js App"/>  -->
    <!-- 搜索框模块 -->
    <div class="clearfix" style="margin-bottom:20px;">
      <div style="width:500px;float:left">
        <el-input placeholder="请输入查询条件" v-model="pageInfo.orgName" class="input-with-select" @keyup.enter.native="search()">
        <el-button slot="append" icon="el-icon-search" @click="search()"></el-button>
        </el-input>
      </div>
      <el-button type="primary" style="float:right" @click="dialogAddVisible = true">上传院校资料</el-button>
    </div>

  <!-- 信息展示模块 -->
  <el-table :data="tableData" borderstyle="width: 100%" border>
    <el-table-column type="index" label="序号" width="180"></el-table-column>
    <el-table-column prop="orgName" label="院校名称" width="180"></el-table-column>
    <el-table-column prop="grade" label="年级" width="180"></el-table-column>
    <el-table-column prop="resType" label="资料类型" width="180"></el-table-column>
    <el-table-column prop="fileList.name" label="文件列表" width="180"></el-table-column>
    

    <el-table-column  label="操作">
      <template slot-scope="scope">
         <!-- :href="scope.row.fileList.url" -->
      <el-link  target="_blank" :underline="false" style="margin-right:10px;">
        <el-button type="primary" icon="el-icon-download" circle @click="downloadImg(scope.row.fileList.url,'pic')"></el-button>
      </el-link>
      <el-button type="primary" icon="el-icon-edit" circle @click="editCollege(scope.row)"></el-button>
      <el-button type="danger" icon="el-icon-delete" circle @click="deleteCollege(scope.row)"></el-button>
      </template>
    </el-table-column>
   
  </el-table>
  <el-pagination style="width:560px" :page-size="pageInfo.size"  layout="prev, pager, next" :pager-count="11"
      :total="total" background 
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageInfo.page">
</el-pagination>


<!-- 添加弹出框模块 -->
  <el-dialog title="上传院校资料" :visible.sync="dialogAddVisible" width="30%">
  <el-form :model="form" :rules="rules" ref="form">
    <el-form-item label="院校名称" :label-width="formLabelWidth">
      <el-select v-model="form.orgName" placeholder="请选择院校名称" style="width:100%">
        <el-option label="河南大学" value="河南大学"></el-option>
        <el-option label="开封大学" value="开封大学"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="年级" :label-width="formLabelWidth">
      <el-select v-model="form.grade" placeholder="请选择年级" style="width:100%">
        <el-option label="2019级" value="2019级"></el-option>
        <el-option label="2020级" value="2020级"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="资料类型" :label-width="formLabelWidth">
      <el-radio-group v-model="form.resType">
        <el-radio label="教学计划表">教学计划表</el-radio>
        <el-radio label="人才培养方案">人才培养方案</el-radio>
        <el-radio label="合同">合同</el-radio>
        <el-radio label="其他">其他</el-radio>
      </el-radio-group>
    </el-form-item>
     <el-form-item style="margin-bottom:0px">
       <!-- multiple -->
      <el-upload class="upload-demo"  ref="upload" :before-upload="beforeUpload" :file-list="form.fileList" drag 
      action="上传的url"  
      :limit="1" :on-exceed="handleExceed" :auto-upload="false">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">文件大小不超过2M</div>
</el-upload>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer" style="text-align:center">
    <!-- <el-button type="primary" @click="addCollege('form')">提交</el-button> -->
    <el-button type="primary" @click="onsuccsess">提交</el-button>
    <el-button @click="dialogAddVisible = false">取 消</el-button>
  </div>
</el-dialog>


<!-- 修改弹出框模块 -->
  <el-dialog title="修改院校资料" :visible.sync="dialogEditVisible" width="30%">
  <el-form :model="editForm" :rules="rules" ref="editForm">
    <el-form-item label="院校名称" :label-width="formLabelWidth">
      <el-select v-model="editForm.orgName" placeholder="请选择院校名称" style="width:100%">
        <el-option label="河南大学" value="河南大学"></el-option>
        <el-option label="开封大学" value="开封大学"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="年级" :label-width="formLabelWidth">
      <el-select v-model="editForm.grade" placeholder="请选择年级" style="width:100%">
        <el-option label="2019级" value="2019级"></el-option>
        <el-option label="2020级" value="2020级"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="资料类型" :label-width="formLabelWidth">
      <el-radio-group v-model="editForm.resType">
        <el-radio label="教学计划表">教学计划表</el-radio>
        <el-radio label="人才培养方案">人才培养方案</el-radio>
        <el-radio label="合同">合同</el-radio>
        <el-radio label="其他">其他</el-radio>
      </el-radio-group>
    </el-form-item>
     <el-form-item >
       <!-- multiple  上传多个加这个属性 -->
      <el-upload class="upload-demo" :before-upload="beforeUpload" :file-list="form.fileList" :on-success="onsuccsess"  drag action="https://jsonplaceholder.typicode.com/posts/" >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">每次只能上传一个文件，且文件大小不超过2M</div>
      </el-upload>
    </el-form-item>
  </el-form>
    <div slot="footer" class="dialog-footer" style="text-align:center">
      <!-- <el-button type="primary" @click="updateCollege('editForm')">提交</el-button> -->
      <el-button type="primary" @click="alert('e')">提交</el-button>

      <el-button @click="dialogEditVisible = false">取 消</el-button>
  </div>      

  
</el-dialog>
  </div>
</template>

<script>


export default {
  name: 'collegeResource',
  data() {
      return {
        pageInfo:{
          page:1,//当前页码
          size:2,//前台默认分页条数
          orgName:""
        },
        total:0,
        select:'',
        dialogAddVisible: false,//控制添加弹窗是否显示
        dialogEditVisible: false,//控制修改弹窗是否显示
        form: {
         orgName: '',
         grade:'',
         resType: '教学计划表',
         address: '',
         fileList: [
          {name: 'food.jpeg', 
          url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'},
         {name: 'food2.jpeg', 
         url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}], 
        },
        //编辑使用的后台查询方法获取的数据，editform必须为空
        editForm: {},
        //添加院校名称的限制规则
        rules: {
          orgName: [
            { required: true, message: '请输入院校名称', trigger: 'blur' },
            {  max: 50, message: '院校名称不能超过50个字符', trigger: 'blur' }
          ]
        },
        formLabelWidth: '120px',
        //显示院校的列表
        tableData: [
          {
            orgName:"开封大学",
            grade:"2019级",
            resType:"教学计划表",
            fileList: {name:"food.jpg",
            url:"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201305%2F30%2F220025pxfkhykvkgkvuktq.jpg&refer=http%3A%2F%2Fattach.bbs.miui.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1613267156&t=03000a40851b50f49c6ea6359199c444"
            }
          },
          {
            orgName:"河南大学",
            grade:"2020级",
            resType:"教学大纲",
            fileList: {
              name:"food1.jpg",
            url:"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201305%2F30%2F220025pxfkhykvkgkvuktq.jpg&refer=http%3A%2F%2Fattach.bbs.miui.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1613267156&t=03000a40851b50f49c6ea6359199c444"
            } }
        ]
      }
    },
  components: {
    // HelloWorld
  },
  created(){
    this.render();//渲染数据
  },
  methods: {
    async render(){ 
      const { data: res } = await this.$http.post('orginfo/findall',this.pageInfo) // 获取数据
      this.total=res.data.recordCount;
      //console.log(res)
      if (res.ret !== 0) {
         return this.$message.error(res.msg)
      }
      this.tableData=res.data.resList;
    },
    //增加院校方法
    addCollege(formName){
      this.$refs[formName].validate(async valid => {
        if (!valid) return
        // 可以发起添加院校的网络请求 
        const { data: res } = await this.$http.post('orginfo/save', this.form)
        //清空添加面板
        this.form.orgName="";
        this.form.linkMan="";
        this.form.linkTel="";
        this.form.areaName="";
        this.form.address="";

        this.$message.success('添加院校成功！')
        // 隐藏添加院校的对话框
        this.dialogAddVisible = false;
        // 重新获取院校列表数据
        //this.render()
      })
    },
     //修改院校弹框带数据方法
    async editCollege(scope){
      this.dialogEditVisible=true;
      //console.log(scope.id);
      const { data: res } = await this.$http.post('orginfo/findById',{id : scope.id})
      //抛出异常错误
      if (res.ret !== 0) {
         return this.$message.error(res.msg)
      }
      this.editForm=res.data;
    },
    //更新院校方法
    async updateCollege(form){
     this.$refs[form].validate(async valid => {
        if (!valid) return
        // 发起修改院校信息的数据请求
        const { data: res } = await this.$http.post('orginfo/update',this.editForm)
        //抛出异常错误
       if (res.ret !== 0) {
         return this.$message.error(res.msg)
      }
        // 关闭对话框
        this.dialogEditVisible=false;
        // 刷新数据列表
        this.render();
        // 提示修改成功
        this.$message.success('更新院校信息成功！')
      })
    },
     // 根据Id删除对应的院校信息
    async deleteCollege(row) {
      // 弹框询问是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将删除该院校所有信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 如果确认删除，则返回值为字符串 confirm
      // 如果取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      //异步数据库删除
      const { data: res } = await this.$http.post('orginfo/deleteById',{id : row.id})
      //抛出异常错误
       if (res.ret !== 0) {
         return this.$message.error(res.msg)
      }

      this.$message.success('删除院校成功！')
      this.render()
    },
    //页面输入页码的处理
    handleSizeChange(val) {
        //console.log(`每页 ${val} 条`);
        //this.pageInfo.page=val;
      },
      //页面更改页码处理函数
    handleCurrentChange(val) {
        //console.log(`当前页: ${val}`);  
        this.pageInfo.page=val;
        //console.log(this.pageInfo.page)
        this.render()
    },
    async search(){
      // 发起模糊查询的数据请求
      const { data: res } = await this.$http.post('orginfo/findall',this.pageInfo)
      //console.log(res)
      this.tableData=res.data.resList;
      this.total=res.data.recordCount;
      //抛出异常错误
      if (res.ret !== 0) {
        return this.$message.error(res.msg)
      }
    },
    download(scope){
     window.location.href=scope
    },
    //this.HOST是本地跨域代理的接口地址
    //src是图片的地址
    downloadImg(src,name){
        var image = new Image();
        // 解决跨域 Canvas 污染问题
        image.setAttribute("crossOrigin", "anonymous");
        image.onload = function() {
            var canvas = document.createElement("canvas");
            canvas.width = image.width;
            canvas.height = image.height;
            var context = canvas.getContext("2d");
            context.drawImage(image, 0, 0, image.width, image.height);
            var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
        
            var a = document.createElement("a"); // 生成一个a元素
            var event = new MouseEvent("click"); // 创建一个单击事件
            a.download = name || "photo"; // 设置图片名称
            a.href = url; // 将生成的URL设置为a.href属性
            a.dispatchEvent(event); // 触发a的单击事件
        };
        // console.log(this.HOST,src)
        image.src = src;
    },
    beforeUpload(file) {       
      var FileExt = file.name.replace(/.+\./, "");       
        if (['jpg','png','txt','zip', 'rar','pdf','doc','docx','xlsx'].indexOf(FileExt.toLowerCase()) === -1){            
          this.$message({ 
            type: 'warning', 
            message: '请上传后缀名为jpg、png、txt、pdf、doc、docx、xlsx、zip或rar的附件！' 
        });                
        return false;       
        } 
        console.log(file.size)
        this.isLt2k = file.size / 1024  < 2000?'1':'0';        
        if(this.isLt2k==='0') {            
          this.$message({                
            message: '上传文件大小不能超过2M!',                
            type: 'error'            
          }); 
          return this.isLt2k==='1'?true: false;         
      }        
	       
    },
    onsuccsess(){
      console.log("1")
    },
    handleExceed(files, fileList) {
      // this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
     this.$message.warning(`当前限制最多上传 1 个文件，请删除已选择文件后再选择文件`);

    },
     
  }
}

</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.el-select .el-input {
    width: 130px;
}
.input-with-select{
   width:500px;
}
.input-with-select .el-input-group__prepend {
    background-color: #fff;  
}
.clearfix{*zoom:1}
.clearfix:after{
  display: block;
  content:"";
  height:0;
  clear: both;
  visibility: hidden;
}
.el-select .el-input{
  width:100%;
  }
#app .el-upload-dragger{
   width:280px;
   height:auto;
}
#app .el-upload-dragger .el-icon-upload{
   margin:auto;

  }
</style>
